package cn.ichiva.web.component;

import cn.ichiva.web.common.Bus;
import cn.ichiva.web.common.Topic;
import com.alibaba.fastjson.JSON;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.VBox;
import javafx.scene.web.PopupFeatures;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

import java.net.URL;
import java.util.HashMap;
import java.util.ResourceBundle;

public class Browser implements Initializable {

    public Browser(){
        Bus.subscribe(Topic.TurnTo,url -> this.open(url));
        Bus.subscribe(Topic.Refresh,url -> this.refresh());
        Bus.subscribe(Topic.Home,url -> this.home());
        Bus.subscribe(Topic.Start,url -> {
            String title = web.getEngine().getTitle();
            HashMap<String, String> map = new HashMap<String, String>() {
                {
                    put("title", title);
                    put("url", url);
                }
            };
            Bus.publish(Topic.Favorite, JSON.toJSONString(map));
        });
    }

    @FXML
    VBox root;

    @FXML
    WebView web;

    public void open(String url){
        double height = root.getHeight();
        web.setMinHeight(height);
        web.setMaxHeight(height);

        if(!(url.indexOf("http") == 0 || url.indexOf("https") == 0)){
            url = "http://" + url;
        }

        web.getEngine().load(url);
        Bus.publish(Topic.ChangeUrl,url);
    }

    public void home() {
        web.getEngine().load( "https://cn.bing.com");
    }

    public void refresh(){
        web.getEngine().reload();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        WebEngine engine = web.getEngine();
        engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
            @Override
            public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
                    String url = engine.getLocation();
                    Bus.publish(Topic.loadUrl,url);
            }
        });
    }

    /**
     * 多窗口支持
     */
    public void win(){
        WebEngine engine = web.getEngine();
        engine.setCreatePopupHandler(config -> {
                    //弹窗处理逻辑
                    return null;
                });

    }
}
